//
//  Memory Save Operation.h
//  Memento 2.0
//
//  Created by Chris Maddocks on 2010-07-18
//  Copyright 2010 Team Memento. All rights reserved.
//
//  10-07-20: Add thread-safe rescaling and rotation code; integrate with save operation.  (C. Maddocks)

#import "MemorySaveOperation.h"


@implementation MemorySaveOperation
@synthesize filePath, image, memory;

- (id)initForMemory:(Memory *)aMemory withImage:(UIImage *)aImage toFilePath:(NSString *)aFilePath  {
    self = [super init];
    if (self) {
        executing = NO;
        finished = NO;

		aMemory.saving = YES;
		
		self.memory = aMemory;
		self.image = aImage;
		self.filePath = aFilePath;
    }
    return self;
}

- (BOOL)isConcurrent {
    return YES;
}

- (BOOL)isExecuting {
    return executing;
}

- (BOOL)isFinished {
    return finished;
}

- (void)start {
	// Always check for cancellation before launching the task.
	if ([self isCancelled])
	{
		// Must move the operation to the finished state if it is canceled.
		[self willChangeValueForKey:@"isFinished"];
		finished = YES;
		[self didChangeValueForKey:@"isFinished"];
		return;
	}
	
	// If the operation is not canceled, begin executing the task.
	[self willChangeValueForKey:@"isExecuting"];
	[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
	executing = YES;
	[self didChangeValueForKey:@"isExecuting"];
}

- (void)main {
	@try {
		NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
		
		// Scale image
		CGSize targetSize = {300,300};
		UIImage *scaledImage = [UIImageScaledToSize(self.image, targetSize) retain];  // Scale image to 300 x 300

		NSData *imageData = [[NSData dataWithData:UIImageJPEGRepresentation(scaledImage, 1)] retain];  // Generate NSData stream for scaled image
		[imageData writeToFile:self.filePath atomically:YES];  // Write to disk
		[imageData release];
		
		memory.saving = NO;
		memory.image = nil;  // Only store the image in memory when we don't have a copy on disk
		
		self.filePath = nil;
		self.image = nil;
		self.memory = nil;

		[scaledImage release];
				
		
		[self completeOperation];
		[pool release];
	}
	@catch(...) {
		// Do not rethrow exceptions.
	}
}

// Given a UIImage and a target size, this function will return a scaled UIImage.  Uses functions in ImageHelpers.h.
UIImage *UIImageScaledToSize(UIImage *image, CGSize toSize) {
	UIImage *scaledImg = nil;
	
	[image retain];
	
	float scale = GetScaleForProportionalResize( image.size, toSize, false, false );
	CGImageRef cgImage = CreateCGImageFromUIImageScaled( image, scale );
	
	[image release];
	
	if (cgImage) {
		scaledImg = [UIImage imageWithCGImage:cgImage]; //autoreleased
		CGImageRelease( cgImage );
	}
	
	return scaledImg;
}



- (void)completeOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
	
    executing = NO;
    finished = YES;
	
    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}


@end


